package cn.tannn.surenessdemo.user.dao;

import cn.tannn.surenessdemo.user.entity.AuthRole;
import cn.tannn.surenessdemo.user.entity.AuthUserRoleBind;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author tan
 * @date 2022-07-18 11:00:57
 */
public interface AuthUserRoleBindDao extends JpaRepository<AuthUserRoleBind, Long> {

    /**
     * 查询当前用户所拥有的角色
     * @param userCode userCode
     * @return role list
     */
    @Query("select ar from AuthRole ar, AuthUserRoleBind bind " +
            "where ar.code = bind.roleCode and bind.userCode = :userCode")
    List<AuthRole> findUserBindRoleList(@Param("userCode") Long userCode);

    /**
     * 删除roleCode和userId等于这个的记录
     * @param roleCode roleCode
     * @param userCode userCode
     */
    @Query("delete from AuthUserRoleBind bind " +
            "where bind.roleCode = :roleCode and bind.userCode = :userCode")
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    void deleteRoleResourceBind(@Param("roleCode") String roleCode,@Param("userCode") String userCode);



    /**
     * 删除角色时删除 角色-用户
     * @param roleCode roleCode
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query("delete from AuthUserRoleBind bind where bind.roleCode = :roleCode")
    void deleteRoleResourceBind(@Param("roleCode") String roleCode);


}
